<?php

namespace app\common\model\Product;

use think\Model;
use traits\model\SoftDelete;

class Product extends Model
{
    // 表名
    protected $name = 'product';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 软删除
    use SoftDelete;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'flag_text',
        'status_text',
        'thumbs_text'
    ];

    public function getFlagList()
    {
        return ['1' => __('新品'), '2' => __('热销'), '3' => __('推荐')];
    }


    public function getFlagTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['flag']) ? $data['flag'] : '');
        $list = $this->getFlagList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusList()
    {
        return ['0' => __('下架'), '1' => __('上架')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getThumbsTextAttr($value, $data)
    {
        //域名地址
        $domian = empty(config('url_domain_root')) ? "http://www.fastadmin.com/" : trim(config('url_domain_root'));
        $domian = trim($domian, "/");

        //给一张默认图片地址
        $default = '/assets/img/avatar.png';

        //拿出头像的字段信息
        $thumbs = isset($data['thumbs']) ? trim($data['thumbs']) : $default;
        $thumbs = is_file(".".$thumbs) ? $thumbs : $default;
        $thumbs = $domian.$thumbs;
        return $thumbs;
    }

    // 分类关联查询
    public function type()
    {
        return $this->belongsTo('app\common\model\Product\Type','typeid','id',[],'LEFT')->setEagerlyType(0);
    }

    // 单位关联查询
    public function unit()
    {
        return $this->belongsTo('app\common\model\Product\Unit','unitid','id',[],'LEFT')->setEagerlyType(0);
    }
}
